//
//  ShopVC.m
//  sensen_ios
//
//  Created by pro on 16/2/2.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ShopVC.h"

// 控制器
#import "ShopSectionsVC.h"
#import "ShopCartVC.h" // 购物车页面
#import "ShopMessageVC.h" // 消息页面
#import "ProductSearchsVC.h"
#import "NewsTotalVC.h"//新闻资讯
// 视图
#import "CarouselView.h" // 轮播视图
#import "ShopSectionView.h" 
// 数据
#import "ProductModel.h"
#import "PostReplyModel.h"

@interface ShopVC ()
{
//    PostReplyModel *_newsModel;
    NSMutableArray *_newsAry;
    NSTimer *_timer;
}
@property (nonatomic, strong) UIScrollView *scrollView; // 滑动视图
@property (nonatomic, strong) UIScrollView *hotScrollView; // 滑动视图

// 滑动视图上的子视图
@property (nonatomic, strong) CarouselView *carouselView; // 轮播视图
@property (nonatomic, strong) UIView *sectionBgView; // 版块分类视图总视图
@property (nonatomic, strong) UIView *hotspotBgView; // 森森热点视图总视图

@end

@implementation ShopVC
- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}
#pragma mark - 控制器方法
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createSearchBar];
    [self createLeftBarButtonItemWithImagename:nil]; // 创建左侧返回按钮
    [self createRightBarButtonItemsWithImagenameAry:@[@"商城首页_购物车",@"商城首页_消息"]];
    
    [self _createViews]; // 创建视图
    
    [self _getData]; // 获得数据
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
    
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
   
}
#pragma mark - 获取数据
- (void)_getData {
    
    // 获得轮播图
    NSDictionary *params = @{@"position" : @18};
    [BoyeHttpClient post:@"BY_Picture_getURL" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {

        // 轮播图不为空
        if (![result isKindOfClass:[NSNull class]]) {
            NSMutableArray *ary = [NSMutableArray array];
            for (NSDictionary *dic in result) {
                CarouselModel *model = [[CarouselModel alloc] initContentWithDic:dic];
                
                [ary addObject:model];
            }

            // 设置轮播图
            _carouselView.modelAry = ary;
        }
        // 轮播图为空
        else {
            // 轮播图为空，则传入一个元素的数组，让轮播图加载默认图片
            _carouselView.modelAry = nil;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 失败
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:2];
    }];
    
    // 获得森森热点
    NSMutableDictionary *newsParams = [NSMutableDictionary dictionaryWithCapacity:0];

//    [newsParams setObject:@1 forKey:@"page_size"];
//    [newsParams setObject:@1 forKey:@"page_no"];
    [newsParams setObject:@"rd" forKey:@"position"];

    _newsAry = [[NSMutableArray alloc] init];
    
    [BoyeHttpClient post:@"BY_News_query" apiVerson:101 params:newsParams success:^(AFHTTPRequestOperation *operation, id result) {
        
        if (![result[@"list"] isKindOfClass:[NSNull class]]) {
            
            NSArray *resultAry = (NSArray *)result[@"list"];
            
            for (NSDictionary *newsDic in resultAry) {
                
                PostReplyModel *newsModel = [[PostReplyModel alloc] init];
                newsModel.fid = newsDic[@"id"];
                newsModel.main_img = newsDic[@"main_img"];
                newsModel.post_excerpt = newsDic[@"post_excerpt"];
                newsModel.post_title = newsDic[@"post_title"];
                NSString *title = newsModel.post_title;
                UILabel *titleLabel = (UILabel *)[_hotspotBgView viewWithTag:6+([resultAry indexOfObject:newsDic])];
                titleLabel.text = title;
                
                [_newsAry addObject:newsModel];
            }
        }
        
        _hotScrollView.contentSize = CGSizeMake(_hotScrollView.width, _hotScrollView.height * _newsAry.count);
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeHotNews) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
    }];

    // 加载8个馆的热门商品
    for (int i = 0; i < 8; i ++) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setObject:@15 forKey:@"group_id"];
        [params setObject:GET_CATE_ID(i) forKey:@"cate_id"];
        [params setObject:@5 forKey:@"page_size"];
     
        [BoyeHttpClient post:@"BY_Product_queryByGroup" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {

            NSMutableArray *modelAry = [[NSMutableArray alloc] init];
            
            if (![result[@"list"] isKindOfClass:[NSNull class]]) {
                for (NSDictionary *dic in result[@"list"]) {
                    ProductModel *model = [[ProductModel alloc] initContentWithDic:dic];
                    
                    [modelAry addObject:model];
                }
            }
            
            // 给图片上数据
            ShopSectionView *view = (ShopSectionView *)[_scrollView viewWithTag:1000+i];
            view.modelAry = modelAry;
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error_%i:%@", i, error);
            [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
        }];
    }
}


#pragma mark - 创建导航栏视图
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItemsWithImagenameAry:(NSArray *)imgnameAry {
    NSArray *titles = @[@"购物车", @"消息"];
    NSMutableArray *itemsAry = [[NSMutableArray alloc] init];
    for (int i = 0; i < imgnameAry.count; i ++) {
        UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 35)];
        customView.userInteractionEnabled = YES;
        customView.tag = i + 1;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
        [customView addGestureRecognizer:tap];
        // 图标
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 20, 20)];
        imgView.userInteractionEnabled = YES;
        imgView.image = [UIImage imageNamed:imgnameAry[i]];
        [customView addSubview:imgView];
        // label
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 30, 15)];
        label.userInteractionEnabled = YES;
        label.font = FONT(10);
        label.text = titles[i];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        [customView addSubview:label];
        
        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
        [itemsAry addObject:rightBarButton];
    }
    self.navigationItem.rightBarButtonItems = itemsAry;
}
// 创建中间的搜索栏
- (void)createSearchBar {
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 80 * 2, 35)];
    searchView.backgroundColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    searchView.layer.cornerRadius = searchView.height / 2.0;

    // 搜索
    UIImageView *searchImgView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, searchView.height - 16, searchView.height - 16)];
    searchImgView.image = [UIImage imageNamed:@"商城首页_搜索"];
    [searchView addSubview:searchImgView];
    
    // 搜索栏输入
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(searchImgView.right + 5, 2, searchView.width - searchView.height / 2, 31)];
    [searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    searchBtn.backgroundColor = [UIColor clearColor];
    [searchBtn setTitle:@"森森购物" forState:UIControlStateNormal];
    searchBtn.titleLabel.font = FONT(14);
    searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [searchView addSubview:searchBtn];
    
    
    self.navigationItem.titleView = searchView;
}

#pragma mark - 创建视图
// 创建主视图
- (void)_createViews {
    
    [self _createScrollView]; // 创建滑动视图
    [self _createTapToTopView]; // 创建返回顶部的按钮
    [self _createCarouselView]; // 创建轮播视图
    [self _createSectionViews]; // 创建版块分类视图
//    [self _createHotspotView]; // 森森热点视图
    [self _createShopSectionViews]; // 图片内容的版块视图
    
    // 遍历滑动视图的子视图，设置滑动范围
    UIView *lastView = _scrollView.subviews.lastObject;
    _scrollView.contentSize = CGSizeMake(0, lastView.bottom);

}
// 滑动视图
- (void)_createScrollView {
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
}
// 轮播视图
- (void)_createCarouselView {
    _carouselView = [[CarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH/2)timerDuration:3 carouselAmount:5];
    [_scrollView addSubview:_carouselView];
}
// 版块分类视图
- (void)_createSectionViews {
    
    NSArray *imgNames = @[@"商城首页_水族馆",
                          @"商城首页_宠物馆",
                          @"商城首页_钓具馆",
                          @"商城首页_景观园艺",
                          @"商城首页_运动休闲",
                          @"商城首页_家居摆件",
                          @"商城首页_花卉园艺",
                          @"商城首页_户外家具",];
    NSArray *titles = @[@"水族馆",
                        @"宠物馆",
                        @"钓具馆",
                        @"景观园艺",
                        @"运动休闲",
                        @"家居摆件",
                        @"花卉园艺",
                        @"户外家具",];
    CGFloat x = 0;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = width / 2.0;
    CGFloat y = _carouselView.bottom;
    
    // 总的视图
    _sectionBgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [_scrollView addSubview:_sectionBgView];
    
    for (int i = 0; i < titles.count; i ++) {
        
        width = SCREEN_WIDTH / 4.0;
        height = width;
        x = (i % 4) * width;
        y = (i / 4) * height;
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        sectionView.tag = 10 + i;
        [_sectionBgView addSubview:sectionView];
        // 添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionViewTap:)];
        [sectionView addGestureRecognizer:tap];

        width *= 0.7;
        height = width;
        x = (sectionView.width - width) / 2.0;
        y = 0;
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        imgView.image = [UIImage imageNamed:imgNames[i]];
        [sectionView addSubview:imgView];
        
        x = 0;
        width = sectionView.width;
        height = 12;
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        titleLabel.userInteractionEnabled = YES;
        titleLabel.font = FONT(12);
        titleLabel.text = titles[i];
        titleLabel.textColor = [UIColor darkGrayColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [sectionView addSubview:titleLabel];
        titleLabel.tag = 100;
        
        // 设置位置
        imgView.top = (sectionView.height - imgView.height - titleLabel.height) / 2.0;
        titleLabel.top = imgView.bottom + 5;
    }
}

// 森森热点
- (void)_createHotspotView {
    
//    CGFloat margin = 3;
//    CGFloat bigWidth = (SCREEN_WIDTH - margin * 3) / 2;
//    CGFloat smallWidth = (bigWidth - margin) / 2;
    
    CGFloat x = 0;
    CGFloat y = _sectionBgView.bottom + 10;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = /* bigWidth + */ 30;
    
    // 总的视图
    _hotspotBgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [_scrollView addSubview:_hotspotBgView];
    
    //分割线
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(x, 0, SCREEN_WIDTH, 1)];
    [_hotspotBgView addSubview:label];
    label.backgroundColor = [UIColor colorWithRGBHex:0xd9d9d9];
    
    
    // 森森热点的标语图片
    height = 20;
    width = height * 3;
    x = 10;
    y = 5;
    UIImageView *titleImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    titleImgView.image = [UIImage imageNamed:@"商城首页_森森热点"];
    [_hotspotBgView addSubview:titleImgView];
    
    // 森森热点的内容
    x = titleImgView.right + 10;
    y = 0;
    width = SCREEN_WIDTH - x - 10;
    height = 30;
    
    //分割线2
    UILabel * label2 = [[UILabel alloc] init];
    [_hotspotBgView addSubview:label2];
    label2.backgroundColor = [UIColor colorWithRGBHex:0xd9d9d9];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(_hotspotBgView.mas_centerY);
        make.left.equalTo(titleImgView.mas_right).offset(5);
        make.size.mas_equalTo(CGSizeMake(1, 20));
    }];
    
    
    
    _hotScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _hotScrollView.contentSize = CGSizeMake(width, height * 3);
    [_hotspotBgView addSubview:_hotScrollView];
    
    for (int i = 0; i < 3; i ++) {
        // 文字
        y = height * i;
        UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, y, width, height)];
        contentLabel.font = FONT(15);
        contentLabel.text = @"";
        contentLabel.textColor = SS_NAVI_ORANGE_COLOR;
        contentLabel.textAlignment = NSTextAlignmentLeft;
        [_hotScrollView addSubview:contentLabel];
        contentLabel.tag = 6 + i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hotTap:)];
        contentLabel.userInteractionEnabled = YES;
        [contentLabel addGestureRecognizer:tap];
    }
    

    /*
    // 图片
    // 第一张
    x = 5;
    y = contentLabel.bottom;
    width = bigWidth;
    height = width;
    UIImageView *firstImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    firstImgView.image = [UIImage imageWithColor:ORANGE_COLOR];
    [_hotspotBgView addSubview:firstImgView];
    firstImgView.tag = 11;
    
    // 第二张
    x = firstImgView.right + margin;
    y = firstImgView.top;
    width = smallWidth;
    height = width;
    UIImageView *sectionImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    sectionImgView.image = [UIImage imageWithColor:BLUE_COLOR];
    [_hotspotBgView addSubview:sectionImgView];
    sectionImgView.tag = 12;
    
    // 第三张
    x = sectionImgView.right + margin;
    UIImageView *thirdImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    thirdImgView.image = [UIImage imageWithColor:[UIColor grayColor]];
    [_hotspotBgView addSubview:thirdImgView];
    thirdImgView.tag = 13;
    
    // 第4张
    x = sectionImgView.left;
    y = sectionImgView.bottom + margin;
    UIImageView *fourthImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    fourthImgView.image = [UIImage imageWithColor:GREEN_COLOR];
    [_hotspotBgView addSubview:fourthImgView];
    fourthImgView.tag = 14;
    
    // 第5张
    x = fourthImgView.right + margin;
    UIImageView *fivethImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    fivethImgView.image = [UIImage imageWithColor:RED_COLOR];
    [_hotspotBgView addSubview:fivethImgView];
    fivethImgView.tag = 15;
     */
    
}

- (void)_createShopSectionViews {
    NSArray *titles = @[@"水族馆",
                        @"宠物馆",
                        @"钓具馆",
                        @"景观园艺",
                        @"运动休闲",
                        @"家居摆件",
                        @"花卉园艺",
                        @"户外家具",];
    NSArray *colors = @[[UIColor colorWithR:30 g:97 b:164],
                        [UIColor colorWithR:119 g:62 b:252],
                        [UIColor colorWithR:241 g:63 b:87],
                        [UIColor colorWithR:97 g:170 b:250],
                        [UIColor colorWithR:71 g:157 b:68],
                        [UIColor colorWithR:217 g:0 b:0],
                        [UIColor colorWithR:246 g:155 b:0],
                        [UIColor colorWithR:243 g:101 b:40]];
    CGFloat x;
    CGFloat y;
    CGFloat width;
    CGFloat height;
    
    for (int i = 0; i < titles.count; i ++) {
        x = 0;
        width = SCREEN_WIDTH;
        height = (SCREEN_WIDTH - 3 * 3) / 2 + 30 + 10;
        y = _sectionBgView.bottom + height * i + 10;
        ShopSectionView *shopSectionView = [[ShopSectionView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        shopSectionView.title = titles[i];
        shopSectionView.titleColor = colors[i];
        shopSectionView.lineColor = [UIColor colorWithRGBHex:0xd9d9d9];
        [_scrollView addSubview:shopSectionView];
        shopSectionView.tag = 1000 + i;
    }
}

// 创建放回顶部的按钮
- (void)_createTapToTopView {
    CGFloat x = SCREEN_WIDTH - 60;
    CGFloat y = SCREEN_HEIGHT - 64 - 49 - 60;
    UIView *tapToTopView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
    tapToTopView.backgroundColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    tapToTopView.alpha = 0.5;
    tapToTopView.layer.cornerRadius = tapToTopView.width / 2;
    tapToTopView.clipsToBounds = YES;
    [self.view insertSubview:tapToTopView aboveSubview:_scrollView];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToTop:)];
    [tapToTopView addGestureRecognizer:tap];
    
    // 添加图片
    x = (40 - 20) / 2.0;
    y  = 0;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 20, 20)];
    imgView.image = [UIImage imageNamed:@"商城首页_返回顶部"];
    [tapToTopView addSubview:imgView];
    // 添加文字
    x = 0;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, tapToTopView.width, 12)];
    titleLabel.userInteractionEnabled = YES;
    titleLabel.font = FONT(8);
    titleLabel.text = @"顶部";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [tapToTopView addSubview:titleLabel];
    
    // 设置位置
    imgView.top = (tapToTopView.height - imgView.height - titleLabel.height) / 2.0;
    titleLabel.top = imgView.bottom;
}



#pragma mark - 滑动事件
- (void)changeHotNews {
    
    [UIView animateWithDuration:0.3 animations:^{
        CGPoint offset = _hotScrollView.contentOffset;
        offset.y += _hotScrollView.height;
        
        _hotScrollView.contentOffset = offset;
        
        if (_hotScrollView.contentOffset.y == _hotScrollView.contentSize.height) {
            _hotScrollView.contentOffset = CGPointMake(0, 0);
        }
    }];
    
    
}

#pragma mark - 点击事件
// 进入搜索页面
- (void)searchAction {
    ProductSearchsVC *vc = [[ProductSearchsVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)rightClick:(UITapGestureRecognizer *)tap {
    // 点击进入购物车页面
    if (tap.view.tag == 1) {
        ShopCartVC *vc = [[ShopCartVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    // 点击进入消息页面
    else if (tap.view.tag == 2) {
        ShopMessageVC *vc = [[ShopMessageVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
// 森森热点点击
- (void)hotTap:(UITapGestureRecognizer *)tap {
    
//    NSInteger index = tap.view.tag - 6;
//    PostReplyModel *newsModel = _newsAry[index];
//    
//    if (newsModel == nil) {
//        return;
//    }
    
    
    NewsTotalVC *vc = [[NewsTotalVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];

    
//    WebVC *vc = [[WebVC alloc] initWithUrlString:[NSString stringWithFormat:@"Post/viewPost?id=%@", newsModel.fid]];
//    vc.titleString = @"森森热点";
//    vc.model = newsModel;
//    [vc createRightBarButtonItemWithImagename:@"论坛首页_详情页_分享"];
//    [self.navigationController pushViewController:vc animated:YES];
}
// 进入下级页面
- (void)sectionViewTap:(UITapGestureRecognizer *)tap {

//    ShopSectionVC *vc = [[ShopSectionVC alloc] init];
    ShopSectionsVC *vc = [[ShopSectionsVC alloc] init];
    vc.type = tap.view.tag - 10;
    [self.navigationController pushViewController:vc animated:YES];
}
// 返回顶部
- (void)tapToTop:(UITapGestureRecognizer *)tap {

    // 滑动到顶部
    [_scrollView setContentOffset:CGPointZero animated:YES];
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
